import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { message } from 'antd';
import { validatePhoneNo, loopEvetyIdCard, formatNumTo2, deepClone, totalDays } from '@/utils';
import { setRealPayPrice } from '@/store/actions/cart';
// css
import styles from '@/styles/ShoppingCart.module.scss';
// 组件
import PayModal from '@/pages_components/pay/PayModal';
import Spin from '@/components/Spin';
// api
import { createCartOrder, orderCartPayH5 } from '@/api/cart';

// 判断产品类型
function productType (projectId){
    switch(projectId){
        case 1: return 'ticketOrderParam';
        case 2: return 'experienceProjectOrderParam';
        case 3: return 'hotelOrderParam';
        default: return '';
    }
}

function $params (){
    return {
        "experienceProjectOrderParam": [],
        "foodProjectParam": [],
        "hotelOrderParam": [],
        "orderCreateRequestParam": [],
        "ticketOrderParam": [],
        "trafficProjectParam": []
    }
}

const CartSettle = ({ _setRealPayPrice, cart: { totalPrice, realPayPrice, reducePrice } }) => {

    const router = useRouter();

    const [num, setNum] = useState(0);
    const [loading, setLoading] = useState(false);
    const [visible, setVisible] = useState(false);
    const [orderId, setOrderId] = useState('');
    const [codeUrl, setCodeUrl] = useState('');

    useEffect(() => {
        let _num = 0, _total = 0, _allReducePrice = 0;
        const dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]');
        dataList.forEach(item => {
            const { goodsCartActivityListDTO, reducePrice } = item;
            goodsCartActivityListDTO.forEach(dto => {
                _num += dto.amount;
                if(dto.projectId == 3){
                    _total += dto.amount*dto.salePrice*totalDays(dto.startDate,dto.endDate);
                }else{
                    _total += dto.amount*dto.salePrice;
                }
            });
            _allReducePrice += (reducePrice || 0);
        });
        setNum(_num);
        _setRealPayPrice({
            totalPrice: formatNumTo2(_total),
            realPayPrice: formatNumTo2(_total-_allReducePrice),
            reducePrice: formatNumTo2(_allReducePrice)
        });
    }, []);

    // 提交订单
    function confirmOrder (){

        const dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]'),
            useCoupon = JSON.parse(sessionStorage.getItem('useCoupon') || '{}'),
            contact = JSON.parse(sessionStorage.getItem('contact') || '{}');

        const { couponId, activityBaseId, activityRuleId, algorithms, saleRole, minusRule, reservationRole } = useCoupon;
        const params = {
            "orderCartActivityItemParamList": [],
            "realPay": +realPayPrice,
            "reducePrice": +reducePrice,
            "totalPrice": +totalPrice
        };

        for (let i = 0; i < dataList.length; i++) {

            const { activityBaseId: _activityBaseId, algorithms: _algorithms, reducePrice: _reducePrice, goodsCartActivityListDTO } = dataList[i];
            const orderCartActivityItemParamList = {
                "activityBaseId": _activityBaseId || 0,
                "algorithms": _algorithms || 0,
                "couponId": 0,
                "itemReducePrice": _reducePrice || 0,
                "orderCartParam": deepClone($params())
            };
            
            for (let j = 0; j < goodsCartActivityListDTO.length; j++) {

                const { id, amount, goodsName, goodsExtendId, projectId, userCanUseCouponDTOList, customersList, startDate, endDate, orderRules = {}, requires } = goodsCartActivityListDTO[j];
                const { realName } = orderRules;
                // ***************  判断条件  *************
                // 需一位实名
                if(realName == 2){
                    if(!customersList || !customersList?.length){
                        message.warning(`“${goodsName}” 需要一名游客提供实名信息`);
                        return
                    }
                }
                // 需每位实名
                if(realName == 3){
                    if(!customersList || !customersList?.length || customersList?.length < amount){
                        message.warning(`“${goodsName}” 需要每位游客提供实名信息`);
                        return
                    }
                }
                // 判断购买限制（儿童、成人、老年票/性别等）
                if(realName > 1){
                    const result = loopEvetyIdCard(realName, customersList, requires, goodsName);
                    if(!result){ return }
                }

                // ****************  组装参数  ****************

                // 产品类型，参数
                let prdType = productType(projectId);
            
                // 定义参数
                let _params = {
                    // 暂时没用的字段
                    channelId: 1,
                    channelName: "",
                    companyId: "",
                    certificateType: "1",
                    distributorPhone: "",
                    managerId: 0,
                    managerName: "",
                    memberId: 0,
                    orderFrom: 2,
                    orderSource: 5,
                    threeOrderNo: "",
                    ticketNo: "",
                    ticketSystemCode: "",
                    userRemark: "",
                    contactDTOS: {},
                    extObject: {},
                    // 优惠券相关
                    activityBaseId: activityBaseId || "",
                    activityRuleId: activityRuleId || "",
                    algorithms: algorithms || "",
                    couponId: orderCartActivityItemParamList['couponId'] || "",
                    saleType: 0,
                    // 需要更新的字段
                    certificateNo: "",
                    customerName: contact.name,
                    phone: contact.phoneNum,
                    extraInformation: {},
                    goodsInfoParamList: [], 
                    cartId: id
                };
               
                // extraInformation 
                _params.extraInformation['useDate'] = startDate;
                if(projectId == 3){ // 酒店
                    _params['comeDate'] = startDate;
                    _params['leaveDate'] = endDate;
                    _params['homeNum'] = amount;
                }
                // goodsInfoParamList 
                if(realName > 1){
                    customersList.forEach(item => {
                        _params['goodsInfoParamList'].push({
                            skuId: goodsExtendId,
                            amount: realName === 3 ? 1 : amount,
                            customerId: item.id,
                            saleId: 0,
                        })
                    })
                }else{
                    _params['goodsInfoParamList'] = [{
                        skuId: goodsExtendId,
                        amount: amount,
                        customerId: 0,
                        saleId: 0,
                    }]
                }

                // 优惠券相关
                if(saleRole){
                    _params['saleType'] = saleRole.saleType;
                }else if(minusRule){
                    _params['saleType'] = minusRule.minusRuleAlgorithmList[0].saleType;
                }else if(reservationRole){
                    _params['saleType'] = reservationRole[0].saleType;
                }

                // 优惠券
                if(userCanUseCouponDTOList?.length && couponId){
                    for (let m = 0; m < userCanUseCouponDTOList.length; m++) {

                        const c = userCanUseCouponDTOList[m];
                        if(c.couponId == couponId){

                            let isRepeat = false;
                            _params['couponId'] = couponId;

                            params['orderCartActivityItemParamList'].forEach(o => {
                                if(o.couponId == couponId){
                                    o['orderCartParam'][prdType].push(_params);
                                    isRepeat = true;
                                }
                            });

                            if(!isRepeat){
                                const _orderCartActivityItemParamList = {
                                    "activityBaseId": 0,
                                    "algorithms": 0,
                                    "couponId": c.couponId,
                                    "itemReducePrice": c.rebatePrice || 0,
                                    "orderCartParam": deepClone($params())
                                }
                                _orderCartActivityItemParamList['orderCartParam'][prdType].push(_params);
                                params['orderCartActivityItemParamList'].push(_orderCartActivityItemParamList);
                            }

                            break;
                        }
                    }
                }else{
                    orderCartActivityItemParamList['orderCartParam'][prdType].push(_params);
                }
            }

            if(orderCartActivityItemParamList?.orderCartParam){
                const _obj = orderCartActivityItemParamList.orderCartParam;
                const _empty = Object.keys(_obj).every(key => !_obj[key].length);
                !_empty && params['orderCartActivityItemParamList'].push(orderCartActivityItemParamList);
            }
        }

        if(!contact.name || !contact.phoneNum){
            message.warning(`请填写联系人/手机号`);
            return
        }
        if (!validatePhoneNo(contact.phoneNum)) {
            message.warning('手机号格式错误');
            return
        }

        // console.log(params);return
        setLoading(true);

        // 创建订单
        createCartOrder(params).then(res => {
            const { code, data: orderId } = res;
            if (code == 0) {
                // 微信支付
                orderCartPayH5(orderId).then(result => {
                    let { data } = result;
                    if(data.code_url){
                        setOrderId(orderId);
                        setCodeUrl(data.code_url);
                        setVisible(true);
                    }else{
                        message.error('发送请求失败，请重试');
                    }
                })
            }
            if(code == 1290){
                message.success('支付成功');
                router.push(`/pay_success?redirect=/`);
            }
            setLoading(false);
        })
    }

    return (
        <>
            <Spin loading={loading} />
            <div className={styles['table-order']}>
                <button onClick={() => { confirmOrder() }}>提交订单</button>
                <span className={styles['amount']}>（已选择<em>{num}</em>件商品）</span>
                <span className={styles['price']}><em>￥</em><b>{realPayPrice}</b></span>
                <span className={styles['title']}>实际支付</span>
            </div>
            <PayModal target="/" visible={visible} setVisible={setVisible} orderId={orderId} codeUrl={codeUrl} />
        </>
    )
}

const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = dispatch => {
    return {
        _setRealPayPrice: v => dispatch(setRealPayPrice(v))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(CartSettle);